package com.authine.cloudpivot.web.api.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Base64;

/**
 * ClassName: HttpClients <br/>
 * Description: <br/>
 * date: 2020/8/25 16:04<br/>
 * @author fj<br />
 * @since JDK 1.8
 */
public class HttpClients {
    /**
     * Description: 使用基于basicAuth认证的get请求
     * @Param: [url, username, password]
     * @Author: fj
     * @Date: 2020/8/25
     * @Return: java.lang.String
     */
    public static String getByBasicAuth(String url, String username, String password) {
        String result = "";
        try {
            // 创建HttpClientBuilder
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
            HttpGet get = new HttpGet(url);
            //添加http头信息
            get.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
            HttpResponse httpResponse = null;
            HttpEntity entity = null;
            try {
                httpResponse = closeableHttpClient.execute(get);
                entity = httpResponse.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 关闭连接
            closeableHttpClient.close();
            System.out.println(result);
        } catch (Exception e) {
            result = "";
        }
        return result;
    }
}
